package com.example.pay.util;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesGcmUtil {
    /**
     * WeChat Pay v3 通知解密：AES-256-GCM
     * @param apiV3Key 32字节Key
     * @param nonce 随机串
     * @param associatedData 附加数据
     * @param cipherText Base64或原始cipher文本（一般已Base64）
     * @return 解密后的明文字符串
     */
    public static String decryptToString(String apiV3Key, String nonce, String associatedData, String cipherText) {
        try {
            byte[] keyBytes = apiV3Key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
            GCMParameterSpec spec = new GCMParameterSpec(128, nonce.getBytes(StandardCharsets.UTF_8));
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            if (associatedData != null) {
                cipher.updateAAD(associatedData.getBytes(StandardCharsets.UTF_8));
            }

            byte[] cipherBytes;
            try {
                cipherBytes = Base64.getDecoder().decode(cipherText);
            } catch (IllegalArgumentException e) {
                cipherBytes = cipherText.getBytes(StandardCharsets.UTF_8);
            }

            byte[] plainBytes = cipher.doFinal(cipherBytes);
            return new String(plainBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("AES-GCM decrypt failed", e);
        }
    }
}